package com.google.googlemarket.utils;

import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.StateListDrawable;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.googlemarket.MyApp;

import java.util.Random;

/**
 * Created by MrGao on 2017/9/17.
 */

public class UiUtils {
    /**
     * dp单位转换为px
     * @param dp
     * @return
     */
    public static int dpd2x(int dp) {
        float density = MyApp.getmContext().getResources().getDisplayMetrics().density;
        int px = (int) (dp * density + 0.5);
        return px;
    }

    public static Drawable createRandomColorSelector() {
        StateListDrawable stateListDrawable = new StateListDrawable();
        //按下状态-正常状态
        int[] pressState = {android.R.attr.state_pressed,android.R.attr.state_enabled};
        int[] normalState = {};

        //按下状态要显示的Drawable
        stateListDrawable.addState(pressState,createRandomColorDrawable());
        stateListDrawable.addState(normalState,createRandomColorDrawable());
        return stateListDrawable;
    }

    private static Drawable createRandomColorDrawable() {
        GradientDrawable drawable = new GradientDrawable();
        drawable.setShape(GradientDrawable.RECTANGLE);
        drawable.setCornerRadius(dpd2x(5));
        drawable.setColor(createRandomColor());
        return drawable;
    }


    /** 创建一个随机颜色 */
    public static int createRandomColor() {
        Random random = new Random();
        int red = 50 + random.nextInt(151);		// 返回50 ~ 200
        int green = 50 + random.nextInt(151);	// 返回50 ~ 200
        int blue = 50 + random.nextInt(151);	// 返回50 ~ 200
        int color = Color.rgb(red, green, blue);
        return color;
    }

    public static TextView createRandomColorTextView(final Activity mContext) {
        TextView textView = new TextView(mContext);
        textView.setGravity(Gravity.CENTER);
        textView.setTextColor(Color.WHITE);
        int padding = dpd2x(6);
        textView.setPadding(padding,padding,padding,padding);
        textView.setBackgroundDrawable(createRandomColorSelector());
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(view.getContext(),((TextView)view).getText(),Toast.LENGTH_LONG).show();
            }
        });
        return textView;
    }
}
